import { message, Modal, Tree } from 'antd'
import { useEffect, useImperativeHandle, useState } from 'react'
import { listItemTYPE, TypeMenuListAPI, TypeUpdatePermissionAPI } from '../../type/api'
import { getMenuListAPI } from '../../api/menuList'
import { setPermissionListAPI } from '../../api/roleListApi'
interface Props {
  mref: React.MutableRefObject<
    | {
        showModal: (data: listItemTYPE) => void
      }
    | undefined
  >
}
function Permission(props: Props) {
  //存储数据列表
  const [dataList, setDataList] = useState<TypeMenuListAPI[]>()
  //存储默认选中的key
  const [defaultKeys, setDefaultKeys] = useState<string[]>([])
  //存储点击的行数据
  const [info, setInfo] = useState<listItemTYPE>()
  //存储修改权限的参数对象
  const [perm, setPerm] = useState<TypeUpdatePermissionAPI>()

  // permissionList.checkedKeys
  useEffect(() => {
    getMenuListAPIFun()
  }, [])
  const getMenuListAPIFun = async () => {
    const res = await getMenuListAPI()
    setDataList(res)
  }
  const [isModalOpen, setIsModalOpen] = useState(false)
  const onCheck = async (checked: any, e: any) => {
    const checkedKeys: string[] = []
    let halfCheckedKeys: string[] = []
    halfCheckedKeys = [...e.halfCheckedKeys]
    setDefaultKeys(checked)

    e.checkedNodes.forEach((item: TypeMenuListAPI) => {
      if (item.menuType !== 1) {
        //是个按钮
        checkedKeys.push(item._id)
      }
    })
    setPerm({
      _id: info?._id,
      permissionList: {
        checkedKeys: checkedKeys,
        halfCheckedKeys: halfCheckedKeys
      }
    })
  }
  const showModal = (data: listItemTYPE) => {
    setPerm({} as TypeUpdatePermissionAPI)
    setIsModalOpen(true)
    setInfo(data)
    setDefaultKeys(data.permissionList.checkedKeys)
  }
  //暴露方法
  useImperativeHandle(props.mref, () => {
    return {
      showModal
    }
  })

  const handleOk = async () => {
    setIsModalOpen(false)

    setPermissionListAPIFun()
  }
  async function setPermissionListAPIFun() {
    console.log(perm)

    await setPermissionListAPI(perm!)
    message.success('修改成功')
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  return (
    <div>
      <Modal title='Basic Modal' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Tree
          checkable={true}
          fieldNames={{
            title: 'menuName',
            key: '_id',
            children: 'children'
          }}
          treeData={dataList}
          checkedKeys={defaultKeys}
          defaultExpandAll={true}
          onCheck={onCheck}
        />
      </Modal>
    </div>
  )
}

export default Permission
